<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/12
 * Time: 18:02
 * 售后
 */
namespace app\api\controller;


use app\common\controller\Api;
use app\common\model\AfterItem;
use app\common\model\DepositRefund;
use app\common\model\Dictionary;
use think\Db;
use think\Exception;

class AfterSales extends Api {
	
	protected $noNeedLogin = [];
	protected $noNeedRight = ['*'];
	/**
	 * 申请售后
	 * @param token 用户标识
	 * @param item_id 订单商品详情ID
	 * @param type 售后类型
	 * @param amount 退款金额
	 * @param content 说明
	 * @param images 图片凭证
	 * @param shipping_no 快递单号
	 * @param shipping_id 物流公司ID
	 * @param goods_status 是否收到货 check接口下发的ID
	 * @param return_id 退款原因 check接口下发的ID
	 * @param wxchange_id 换货原因 check接口下发的ID
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @throws \think\exception\PDOException
	 */
	public function apply(){
		
		$id = input('post.item_id');
		$type = input('post.type');
		$amount = input('post.amount',0);
		$content = input('post.content');
		$images = input('post.images');
		$shippingNo = input('post.shipping_no');
		$shippingId = input('post.shipping_id');
		$goodsStatus = input('post.goods_status_id');
		$returnId = input('post.return_id');
		$exchangeId = input('post.exchange_id');
		
		$userId = $this->auth->id;
		
		!$id && $this->error('请选择申请售后的商品');
		
		!$type && $this->error('请选择售后类型');
		
		
		$model = new \app\common\model\AfterSales();
		
		if($type == $model::TYPE_ONLY_MONEY) {
			!$goodsStatus && $this->error('请选择货物状态');
			!$returnId && $this->error('请选择退款原因');
			!$amount && $this->error('请选择退款金额');
		} elseif($type == $model::TYPE_MONEY_PRODICT) {
			!$returnId && $this->error('请选择退款原因');
			!$amount && $this->error('请选择退款金额');
		} elseif($type == $model::TYPE_EXCHANGE) {
			!$exchangeId && $this->error('请选择换货原因');
		}
		
		if($type == $model::TYPE_MONEY_PRODICT || $type == $model::TYPE_EXCHANGE) {
			!$shippingId && $this->error('请选择快递公司');
			!$shippingNo && $this->error('请填写快递单号');
		}
		
		$goods = Db::name('orderGoods')->alias('g')
			->join('order o', 'g.order_id = o.id', 'left')
			->field('g.number, g.price, o.id as order_id, o.order_no, o.freight, o.business_id')
			->where(['g.id' => $id, 'o.user_id' => $userId])
			->find();
		
		if(!$goods) {
			$this->error('售后商品不存在');
		}
		
		$totalAmount = $goods['number']*$goods['price']+$goods['freight'];
		
		if($amount > $totalAmount) {
			$this->error('最多退款金额'.$totalAmount);
		}
		
		
		//查找该订单商品是否存在未完成售后
		$row = $model->where(['order_id' => $goods['order_id'], 'order_item_id' => $id, 'status' => ['neq', $model::STATUS_FINISH]])->find();
		if($row) {
			$this->error('该商品已申请售后');
		}
		
		$data = [
			'order_id' => $goods['order_id'],
			'business_id' => $goods['business_id'],
			'order_item_id' => $id,
			'type' => $type,
			'amount' => $amount,
			'content' => $content,
			'images' => $images,
			'user_id' => $userId,
			'status' => $model::STATUS_WAIT_BUS,
			'goods_status' => $goodsStatus,
			'return_id' => $returnId,
			'exchange_id' => $exchangeId,
			'shipping_id' => $shippingId,
			'shipping_no' => $shippingNo,
		];
		
		$model->startTrans();
		try {
			
			//添加售后记录
			$afterId = $model->isUpdate(false)->save($data);
			if(!$afterId) {
				throw new Exception('添加售后记录出错，请稍候重试');
			}
			
			$afterId = $model->getLastInsID();
			
			$itemModel = new AfterItem();
			//添加详情记录
			
			$itemRes = $itemModel->addItem($afterId, $itemModel::ROLE_USER,'用户申请售后', '用户申请售后,等待卖家处理');
			if(!$itemRes) {
				throw new Exception('添加售后详情出错，请稍候重试');
			}
			
			$model->commit();
			$this->success('申请成功，等待处理', ['id' => $afterId]);
		} catch (Exception $e) {
			
			$model->rollback();
			$this->error($e->getMessage());
		}
	}
	
	/**
	 * 售后列表
	 */
	public function index(){
		$userId = $this->auth->id;
		
		$list = Db::name('after_sales')->alias('a')
			->join('fs_order_goods g', 'a.order_item_id = g.id', 'left')
			->join('fs_business b', 'g.business_id = b.id', 'left')
			->field('a.id, g.original_image, g.goods_name, g.spec_name, a.type, a.status, a.result, g.business_id, b.name as business_name')
			->where(['a.user_id' => $userId])
			->order(['a.create_time' => 'DESC'])
			->select();
		
		if($list) {
			$model = new \app\common\model\AfterSales();
			$type = $model->getTypeList();
			$status = $model->getStatusList();
			$result = $model->getResultList();
			foreach($list as $key => $value){
				$list[$key]['type_text'] = $type[$value['type']];
				$list[$key]['status_text'] = $status[$value['status']];
				$list[$key]['result_text'] = isset($result[$value['result']])?$result[$value['result']]:'';
				
			}
		}
		$this->success('查询成功', $list);
	}
	
	/**
	 * 详情
	 */
	public function detail(){
		$userId = $this->auth->id;
		$id = input('post.id');
		if(!$id) {
			$this->error('参数错误');
		}
		$list = Db::name('after_sales')->alias('a')
			->join('order_goods g', 'a.order_item_id = g.id', 'left')
			->join('dictionary dg', 'a.goods_status = dg.id', 'left')
			->join('dictionary dr', 'a.return_id = dr.id', 'left')
			->join('dictionary de', 'a.exchange_id = de.id', 'left')
			->join('shipping s', 'a.shipping_id = s.id', 'left')
			->field('
				g.original_image,
				g.goods_name,
				g.spec_name,
				a.id,
				a.amount,
				a.type,
				a.status,
				a.result,
				from_unixtime(a.create_time) as create_time,
				a.content,
				a.shipping_no,
				dg.name as goods_status,
				dr.name as return_reason,
				de.name as exchange_reason,
				s.name as shipping_name
				')
			->where(['a.user_id' => $userId, 'a.id' => $id])
			->find();
		if(!$list) {
			$this->error('售后记录不存在');
		}
		
			$model = new \app\common\model\AfterSales();
			$type = $model->getTypeList();
			$status = $model->getStatusList();
			$list['type_text'] = $type[$list['type']];
			$list['status_text'] = $status[$list['status']];
			
			$item = Db::name('after_item')->where(['after_id' => $id])->select();
			if($item) {
				foreach($item as $k => $v) {
					$item[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
					$item[$k]['role'] = AfterItem::$_role[$v['role']];
				}
			}
			$list['item'] = $item;
			//到期时间
		$list['end_time'] = '';
		
		if($list['status'] == $model::STATUS_WAIT_BUS) {
			//查找设置的售后商家处理时间
			$setting = Db::name('SettingTime')->find(3);
			if($setting) {
				$createTime = strtotime($list['create_time']);
				$times = $setting['days']*24*3600+$setting['hour']*3600+$setting['minute']*60+$setting['second'];
				$list['end_time'] = date('Y-m-d H:i:s', $createTime+$times);
			}
		}
		$this->success('查询成功', $list);
	}
	
	/**
	 * 取消
	 */
	public function cancel(){
		$userId = $this->auth->id;
		$id = input('post.id');
		if(!$id) {
			$this->error('参数错误');
		}
		$row = Db::name('after_sales')->alias('a')
			->join('order_goods g', 'a.order_item_id = g.id', 'left')
			->where(['a.user_id' => $userId, 'a.id' => $id])
			->find();
		if(!$row) {
			$this->error('售后记录不存在');
		}
		
		//更改售后状态
		$model = new \app\common\model\AfterSales();
		if($row['status'] == $model::STATUS_CANCEL || $row['status'] == $model::STATUS_FINISH) {
			$this->error('该记录不可撤销');
		}
		
		$model->startTrans();
		$res = $model->save(['status' => $model::STATUS_CANCEL, 'update_time' => time()], ['id' => $id]);
		if(!$res) {
			$model->rollback();
			$this->error('撤销出错');
		}
		
		//记录历史
		$itemModel = new AfterItem();
		$itemRes = $itemModel->addItem($id, $itemModel::ROLE_USER, '用户撤销售后申请','用户撤销售后申请,售后结束');
		if(!$itemRes) {
			$model->rollback();
			$this->error('记录详情出错');
		}
		
		$model->commit();
		$this->success('撤销成功');
	}
	
	/**
	 * 检查申请售后的商品
	 * @param token 用户token
	 * @param order_id 订单ID
	 * @param item_id 订单详情ID
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function check(){
		$userId = $this->auth->id;
		$orderId = input('post.order_id');
		$itemId = input('post.item_id');
		
		if(!$orderId || !$itemId) {
			$this->error('参数错误');
		}
		
		//查找订单的商品是否存在
		$row = Db::name('orderGoods')->alias('og')
			->join('order o', 'og.order_id = o.id', 'left')
			->where(['o.user_id' => $userId, 'og.order_id' => $orderId, 'og.id' => $itemId])
			->field('o.order_status, o.shipping_status, o.pay_status, og.goods_name, og.spec_name, og.original_image, og.price, og.freight')
			->find();
		if(!$row) {
			$this->error('售后商品不存在');
		}
		
		//查找是否存在未完成的售后
		$afterModel = new \app\common\model\AfterSales();
		$after = Db::name('afterSales')
			->where(['user_id' => $userId, 'order_id' => $orderId, 'order_item_id' => $itemId])
			->order(['create_time' => 'desc'])
			->find();
		if($after && $after['status'] != $afterModel::STATUS_FINISH && $after['status'] != $afterModel::STATUS_CANCEL){
			$this->success('该商品存在未完成售后',$after,201);
		}
		
		$dicModel = Db::name('Dictionary');
		//货物状态
		$goods_status = $dicModel
			->where(['parent_id' => $afterModel::DICTIONARY_GOODS_STATUS_ID])
			->field('id,name')
			->select();
		//退款原因
		$return_money_reason = $dicModel
			->where(['parent_id' => $afterModel::DICTIONARY_RETURN_MONEY_REASON_ID])
			->field('id,name')
			->select();
		//换货原因
		$exchange_reason = $dicModel
			->where(['parent_id' => $afterModel::DICTIONARY_EXCHANGE_REASON_ID])
			->field('id,name')
			->select();
		
		
		//快递公司
		$shippings = Db::name('shipping')
			->where(['status' => 1])
			->field('id, name')
			->order(['sort' => 'ASC', 'name' => 'ASC'])
			->select();
		$returnData = [
			'goods_status' => $goods_status,
			'return_money_reason' => $return_money_reason,
			'exchange_reason' => $exchange_reason,
			'goods' => $row,
			'shippings' => $shippings,
		];
		
		$this->success('查询成功', $returnData);
	}
	
	
	/**
	 * 申请客服介入
	 * @param token 用户token
	 * @param id 售后ID
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @throws \think\exception\PDOException
	 */
	public function applyService(){
		$id = input('post.id');
		!$id && $this->error('参数错误');
		
		$userId = $this->auth->id;
		
		$model = new \app\common\model\AfterSales();
		$row = $model
			->where(['id' => $id, 'user_id' => $userId])
			->find();
		
		!$row && $this->error('售后信息不存在');
		
		if($row['status'] != $model::STATUS_BUS_DISAGREE) {
			$this->error('请等待商家处理后再申请客服介入');
		}
		
		$row['status'] = $model::STATUS_PLATFORM_JOIN;
		$res = $row->save();
		if($res) {
			//记录历史
			$itemModel = new AfterItem();
			$itemRes = $itemModel->addItem($id, $itemModel::ROLE_USER, '客服介入','用户申请客服介入');
			if(!$itemRes) {
				$model->rollback();
				$this->error('记录详情出错');
			}
			
			$this->success('申请成功，等待客服处理');
		} else {
			$this->error('申请出错，请稍候重试');
		}
	}
	
	
	/**
	 * 押金商品退押金
	 */
	public function depositRefund() {
		$userId = $this->auth->id;
		$orderId = input('post.order_id', '', 'intval');
		!$orderId && $this->error('请选择要退款的订单');
		
		$shippingId = input('post.shipping_id', '', 'intval');
		!$shippingId && $this->error('请选择物流公司');
		
		$shippingNo = input('post.shipping_no');
		!$shippingNo && $this->error('请填写物流单号');
		
		$order = Db::name('order')
			->where(['user_id' => $userId, 'id' => $orderId, 'order_prom_type' => \app\common\model\Order::ORDER_TYPE_DEPOSIT])
			->find();
		
		!$order && $this->error('订单不存在');
		
		if($order['order_status'] != \app\common\model\Order::STATUS_SIGN) {
			$this->error('该订单不可进行此操作');
		}
		
		$row = Db::name('depositRefund')
			->where(['user_id' => $userId, 'order_id' => $orderId])
			->find();
		
		$model = new DepositRefund();
		
		$remark = input('post.remark');
		
		if($row) {
			if($row['status'] == $model::STATUS_W) {
				$this->error('退款审核中，请勿重复申请');
			}
			
			if($row['status'] == $model::STATUS_Y){
				$this->error('该订单已经退款');
			}
			
			$res = $model->save([
				'shipping_id' => $shippingId,
				'shipping_no' => $shippingNo,
				'user_remark' => $remark,
				'status' => $model::STATUS_W
			], ['id' => $row['id']]);
		} else {
			$goods = Db::name('orderGoods')->where(['order_id' => $orderId])
				->find();
			$res = $model->isUpdate(false)->save([
				'order_id' => $orderId,
				'user_id' => $userId,
				'order_goods_id' => $goods['id'],
				'shipping_id' => $shippingId,
				'shipping_no' => $shippingNo,
				'user_remark' => $remark,
			]);
		}
		
		if($res) {
			$this->success('申请成功，等待后台审核');
		} else {
			$this->error('申请出错，请稍候重试');
		}
	}
	
	
}
